package leetcode.hard.maxvalueafterreverse;

import util.annotation.Cheated;

/**
 * <a href="https://leetcode.cn/problems/reverse-subarray-to-maximize-array-value/">链接</a>
 */
@Cheated
public class Solution {
    public int maxValueAfterReverse(int[] nums) {
        int arrValue = 0;
        int n = nums.length;
        for (int i = 0; i < n - 1; i++) {
            arrValue += Math.abs(nums[i] - nums[i + 1]);
        }
        int maxValue = arrValue;
        for (int i = 0; i < n - 1; i++) {
            int increase1 = Math.abs(nums[0] - nums[i + 1]) - Math.abs(nums[i] - nums[i + 1]);
            int increase2 = Math.abs(nums[i] - nums[n - 1]) - Math.abs(nums[i] - nums[i + 1]);
            maxValue = Math.max(maxValue, arrValue + Math.max(increase1, increase2));
        }
        int smaller = Integer.MIN_VALUE, larger = Integer.MAX_VALUE;
        for (int i = 0; i < n - 1; i++) {
            smaller = Math.max(smaller, Math.min(nums[i], nums[i + 1]));
            larger = Math.min(larger, Math.max(nums[i], nums[i + 1]));
        }
        maxValue = Math.max(maxValue, arrValue + 2 * (smaller - larger));
        return maxValue;
    }
}
